package org.leetcode.middle.leetcode138;

import org.leetcode.easy.ListNode;

import java.util.HashMap;

public class Solution {


    public Node copyRandomList2(Node head){

        if (head==null){
            return head;
        }

        Node node = head;

        //key为head中的节点，节点上包含了next和random。value为head节点的副本，只有val属性。
        HashMap<Node,Node> hashMap =new HashMap<>();

        while (node!=null){
            hashMap.put(node,new Node(node.val));
            node = node.next;
        }

        node=head;

        //对节点副本的next和random进行指定
        while (node!=null){
            Node copyNode = hashMap.get(node);

            copyNode.next=hashMap.get(node.next);
            copyNode.random=hashMap.get(node.random);

            node=node.next;
        }

        return hashMap.get(head);

    }
    public Node copyRandomList(Node head) {

        if (head==null) {
            return null;
        }

        Node current = head;

      HashMap<Node,Node> map = new HashMap<>();

        while (current!=null)
        {
            map.put(current,new Node(current.val));
            current=current.next;
        }

        current=head;

        while (current!=null)
        {
            map.get(current).next=map.get(current.next);
            map.get(current).random=map.get(current.random);

            current=current.next;
        }


        return map.get(head);
    }
}
